<template>
	<div class="content">
		<el-form  size="small"  ref="ruleFormRef" :rules="rules" class="userInfoContent" :model="formUser" label-width="auto" style="max-width: 600px">
			<el-row :gutter="20">
				<el-col span="12">
					<el-form-item label="账号" prop="userName">
					  <el-input v-model="formUser.userName" />
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="昵称" prop="nickName">
					  <el-input v-model="formUser.nickName" autofocus/>
					</el-form-item>
				</el-col>
			</el-row>
		    <el-row  :gutter="20">
		    	<el-col span="12">
		    		<el-form-item label="手机号" prop="phone">
		    		  <el-input v-model="formUser.phone" maxlength="11" type="number" />
		    		</el-form-item>
		    	</el-col>
		    	<el-col  span="12">
		    		<el-form-item label="邮箱" prop="email">
		    		  <el-input v-model="formUser.email" />
		    		</el-form-item>
		    	</el-col>
		    </el-row>
			<el-row :gutter="20" style="justify-content: space-between;">
				<el-col  span="12">
					<el-form-item label="状态" prop="status">
					  <el-switch v-model="formUser.status" active-value="1" inactive-value="0" />
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="性别" prop="sex">
					  <el-radio-group v-model="formUser.sex">
					    <el-radio value="1">男</el-radio>
					    <el-radio value="0">女</el-radio>
					  </el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="部门"  prop="deptId">
			   <el-tree-select
			      v-model="formUser.deptId"
			      :data="dataDept"
            :default-expanded-keys="[formUser.deptId]"
			      check-strictly
			      :render-after-expand="false"
			   />
			</el-form-item>
      <el-form-item label="岗位"  prop="postIds">
        <el-select multiple v-model="formUser.postIds" placeholder="请选择岗位">
          <el-option
              v-for="item in postData"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
        </el-select>
      </el-form-item>
			<el-form-item label="角色" prop="roleIds">
			  <el-select multiple v-model="formUser.roleIds" placeholder="请选择角色">
			    <el-option
						v-for="item in roleData"
				        :key="item.id"
				        :label="item.roleName"
				        :value="item.id"/>
			  </el-select>
			</el-form-item>
		    <el-form-item label="备注" prop="remark">
		      <el-input v-model="formUser.remark" type="textarea" />
		    </el-form-item>
		</el-form>
	</div>
  <div style="text-align:center" v-if="formUser.id !=1">
    <el-button  size="small"  plain icon="Edit"  style="margin-left:180px;border-color: white;margin-right:20px;" type="primary" @click="onSubmit(ruleFormRef)">保存</el-button>
    <el-button  size="small"  plain icon="Refresh"  style="color: darkgray;margin-right:20px;"  @click="resetForm(ruleFormRef)" >重置</el-button>
    <el-button  size="small"  plain type="info"  @click="close" >取消</el-button>
  </div>
</template>

<script lang="ts" setup>
	import { reactive,ref, defineProps,toRefs,onMounted,watch, watchEffect} from 'vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import {ElMessage,ElMessageBox } from 'element-plus'
	import { edit, info } from '@/api/user.ts';
	import {treelist} from '@/api/dept.ts'
	import {list} from '@/api/role.ts'
  import {postlist} from "@/api/post.ts";
	const emit = defineEmits(['closeEditUserForm','success'])
	const props = defineProps(['userId'])
	

	interface RuleForm {
	  id:number,
	  userName: string
	  nickName: string
	  sex: string
	  status: string
	  email: string
	  deptId: any
	  remark: string
	  roleIds: Array<Number>
	  postIds: Array<Number>
	  phone: string
	}
	const ruleFormRef = ref<FormInstance>()
	const formUser = reactive<RuleForm>({
	  id:0,
	  userName: '',
	  nickName: '',
	  sex: '0',
	  status: '1',
	  email: '',
	  deptId: null,
	  remark: '',
	  roleIds:  [],
    postIds:[],
	  phone: '',
	})
	watchEffect(() => {
	  // 在 3.5 之前只运行一次
	  // 在 3.5+ 中在 "foo" prop 变化时重新执行
	  info({'id':props.userId}).then((res)=>{
	  	if(res.code === 200){
			formUser.id = res.data.id
	  		formUser.userName=res.data.userName
	  		formUser.nickName=res.data.nickName
	  		formUser.sex=res.data.sex
	  		formUser.status=res.data.status
	  		formUser.email=res.data.email
	  		formUser.deptId=res.data.deptId
	  		formUser.remark=res.data.remark
	  		formUser.roleIds=res.data.roleIds
	  		formUser.postIds=res.data.postIds
	  		formUser.phone=res.data.phone
	  		
	  	}
	  })
	})
	
	
	const rules = reactive<FormRules<RuleForm>>({
		nickName:[{required:true,message:'昵称不能为空',trigger:'blur'},
				  { min: 3, max: 5, message: '长度请输入 3 - 5位', trigger: 'blur' }],
		deptId:[{required:true,message:'部门不能为空',trigger:'blur'}],
		roleIds:[{required:true,message:'角色不能为空',trigger:'blur'}],
		userName:[{required:true,message:'账号不能为空',trigger:'blur'}]
	})
	
	
	const onSubmit = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.validate(async (valid, fields) => {
	    if (valid) {
	      console.log('submit!')
		  const {code} = await edit(formUser);
		  console.log("的："+code)
		  if(code === 200){
			  ElMessage({
			    type: 'success',
			    message: '保存成功',
			  })
			  emit('success')
		  }
	    } else {
	      console.log('error submit!', fields)
	    }
	  })
	}
	
	const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}
	const close = ()=>{
		 emit('closeEditUserForm')
	}
	const dataDept=ref([{value:0,label:'顶级部门',children:[]}])
	const deptData=()=>{
		treelist().then((res)=>{
			if(res.code === 200){
				dataDept.value[0].children = res.data
			}
		})
	}
	const roleData =ref([])
	const getRoleData = ()=>{
		list({"status":"1"}).then((res)=>{
			if(res.code === 200){
				roleData.value = res.data;
			}
		})
	}
  const postData =ref([])
  const getPostData = ()=>{
    postlist({"status":"1"}).then((res)=>{
      if(res.code === 200){
        postData.value = res.data;
      }
    })
  }
	onMounted(()=>{
		deptData();
		getRoleData();
    getPostData()
	})
</script>

<style scoped>
	.content{
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.userInfoContent{
		/* background-color: red; */
	}
</style>